// swtp
package util

import (
	"errors"
	"fmt"
	"html/template"
	"io"
	"io/ioutil"
	"log"
	"path"
	"strings"
	"swim/lang"
)

const (
	TEMPLATE_DIR = "./views"
)

var templates map[string]*template.Template = make(map[string]*template.Template)

func init() {
	fileInfoArr, err := ioutil.ReadDir(TEMPLATE_DIR)
	if err != nil {
		panic(err)
		return
	}
	var templateName, templatePath string
	for _, fileInfo := range fileInfoArr {
		templateName = fileInfo.Name()
		var ext string
		if ext = path.Ext(templateName); ext != ".html" {
			continue
		}
		templatePath = TEMPLATE_DIR + "/" + templateName
		log.Println("Loading template:", templatePath)
		t := template.Must(template.ParseFiles(templatePath))
		tmpl := strings.TrimSuffix(templateName, ext)
		templates[tmpl] = t
	}
}
func RenderHtml(w io.Writer, tmpl string, data interface{}) error {
	var err error
	t := templates[tmpl]
	if t != nil {
		err = t.Execute(w, data)
	} else {
		err = errors.New("template " + tmpl + " not exist")
	}
	return err
}

func RenderOnceHtml(w io.Writer,
	tmpl string, data interface{}) error {
	var terr error
	tFile := fmt.Sprintf(tmpl + ".html")
	//log.Println(tFile)
	t, err := template.ParseFiles(tFile)
	if err == nil {
		terr = t.Execute(w, data)
		return nil
	} else {
		log.Fatal(err)
	}

	return terr
}

//功能:消息提示后返回
//资源文件定义strMsgDef
func WriteMsgBack(w io.Writer, strMsgDef, sLang string) {
	hintMap := make(map[string]interface{})
	hintMap["msg"] = lang.GetText(strMsgDef, sLang)
	RenderHtml(w, sLang+"hintback", hintMap)
}

//功能：直接跳转模板函数
func Redirect(w io.Writer, sUrl string) error {
	locals := make(map[string]interface{})
	locals["url"] = sUrl
	return RenderHtml(w, "redirect", locals)
}

//功能:写错误信息
//sTitle：标题资源标签
//sContent:内容资源标签
func WriteErrorMsg(w io.Writer, sTitle, sContent, sLang string) {
	err_info := make(map[string]interface{})
	err_info["eTitle"] = lang.GetText(sTitle, sLang)
	err_info["eContent"] = lang.GetText(sContent, sLang)
	RenderHtml(w, sLang+"error", err_info)
}
